package com.wryyyyy.utils;

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求方式（GET或POST）
        String method = request.getMethod();
        // 获取请求路径
        String path = request.getRequestURI();
        String s = path.split("/", 0)[1];
        // 根据请求方式+路径判断是否放行
        if (method.equals("GET") && s.equals("dish")) {
            return true;
        }

        // 1.判断是否要拦截（threadLocal中是否有用户）
        if (UserHolder.getUser() == null) {
            response.setStatus(401);
            return false;
        }

        return true;
    }

    @Override //校验完之后，销毁用户信息避免内存泄漏
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //移除用户
        UserHolder.removeUser();
    }
}